﻿// <copyright file="ServerDetailsControl.xaml.cs" company="Soumya Chattopadhyay">
// Copyright (c) 2010 All Right Reserved
// </copyright>
// <disclaimer> This software is intented for educational purposes only and not for 
// commerical or prodution use. The software is provided "as is", without warranty 
// of any kind, express or implied, including but not limited to the warranties of 
// merchantability, fitness for a particular purpose and noninfringement. In no event 
// shall the author(s) or copyright holder(s) be liable for any claim, damages or other 
// liability, whether in an action of contract, tort or otherwise, arising from, out of 
// or in connection with the software or the use or other dealings in the software.
// </disclaimer>

namespace My.CodePlex.TFSExplorer.Controls
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Threading;
    using System.Windows.Controls;
    using System.Windows.Shapes;
    using Microsoft.TeamFoundation.VersionControl.Client;
    using My.CodePlex.TFSExplorer.Resources;
    using My.CodePlex.TFSExplorer.TeamFoundation;

    /// <summary>
    /// Interaction logic for ServerDetailsControl.xaml
    /// </summary>
    public partial class ServerDetailsControl : UserControl, IExplorerControl
    {
        #region Fields

        /// <summary>
        /// Thread that populates the pending changes
        /// </summary>
        private Thread populatePendingChangesThread;

        /// <summary>
        /// Thread to get all the server items
        /// </summary>
        private Thread getAllItemsThread;

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the ServerDetailsControl class
        /// </summary>
        public ServerDetailsControl()
        {
            InitializeComponent();

            this.ControlName = Resource.ServerDetailsControlName;
            this.Header = Resource.ServerDetailsTabItemHeader;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets  the control name
        /// </summary>
        public string ControlName { get; set; }

        /// <summary>
        /// Gets or sets the control tab item header
        /// </summary>
        public string Header { get; set; }

        #endregion

        #region Public methods

        /// <summary>
        /// Populate the pending changes listview
        /// </summary>
        /// <param name="tfsContext">The TFS context</param>
        public void Populate(TeamFoundationContext tfsContext)
        {
            // Set up the thread to populate the source tree view
            this.populatePendingChangesThread = new Thread(this.PopulatePendingChangesView);
            this.populatePendingChangesThread.SetApartmentState(ApartmentState.STA);
            this.populatePendingChangesThread.Start(TeamFoundationContext.CurrentProject.ServerItem);

            this.getAllItemsThread = new Thread(this.GetAllItems);
            this.getAllItemsThread.SetApartmentState(ApartmentState.STA);
            this.getAllItemsThread.Start();
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Get the all the server items
        /// </summary>
        private void GetAllItems()
        {
            ItemSet itemSet = TeamFoundationContext.VersionControlServer.GetItems(TeamFoundationContext.CurrentProject.ServerItem, VersionSpec.Latest, RecursionType.Full, DeletedState.NonDeleted, ItemType.Any);

            Item[] itemArray = itemSet.Items;
            int file = 0;
            int folder = 0;

            Dictionary<string, int> extesions = new Dictionary<string, int>();

            foreach (var item in itemArray)
            {
                if (item.ItemType == ItemType.File)
                {
                    file++;
                }
                else if (item.ItemType == ItemType.Folder) 
                { 
                    folder++; 
                }

                string ext = System.IO.Path.GetExtension(item.ServerItem);

                if (!extesions.ContainsKey(ext))
                {
                    extesions.Add(ext, 1);
                }
                else
                {
                    extesions[ext]++;
                }
            }

            StringBuilder sb = new StringBuilder();

            foreach (var it in extesions.Keys)
            {
                string ext = string.Empty;
                if (string.IsNullOrEmpty(it))
                {
                    ext = "No extension";
                }
                else
                {
                    ext = it;
                }

                sb.Append(ext + " (" + extesions[it].ToString() + "); ");
            }

            this.TotalFiles.Dispatcher.BeginInvoke((Action)(() =>
            {
                this.TotalFiles.Text = file.ToString();
                this.TotalFolders.Text = folder.ToString();
                this.FileExtensions.Text = sb.ToString();
            }));
        }

        /// <summary>
        /// Populate the pending changes listview
        /// </summary>
        /// <param name="data">The name of the topmost folder</param>
        private void PopulatePendingChangesView(object data)
        {
            Workstation currentWorkstation = Workstation.Current;
            WorkspaceInfo[] allWorkspaces = currentWorkstation.GetAllLocalWorkspaceInfo();

            string[] globalperms = TeamFoundationContext.VersionControlServer.GetEffectiveGlobalPermissions(TeamFoundationContext.CurrentDisplayUser);
            string[] effectiveperms = TeamFoundationContext.VersionControlServer.GetEffectivePermissions(TeamFoundationContext.CurrentDisplayUser, TeamFoundationContext.CurrentProject.ServerItem);

            this.ServerName.Dispatcher.BeginInvoke((Action)(() =>
            {
                this.ServerName.Text = TeamFoundationContext.TeamFoundationServer.Name;
                this.ServerUri.Text = TeamFoundationContext.TeamFoundationServer.Uri.ToString();
                this.SessionId.Text = TeamFoundationContext.TeamFoundationServer.SessionId.ToString();
                this.InstanceId.Text = TeamFoundationContext.TeamFoundationServer.InstanceId.ToString();
                this.Culture.Text = TeamFoundationContext.TeamFoundationServer.Culture.DisplayName;
                this.LoggedUser.Text = TeamFoundationContext.TeamFoundationServer.AuthenticatedUserName;
                this.ComputerName.Text = TeamFoundationContext.Workspace.Computer;

                StringBuilder sb = new StringBuilder();
                foreach (string map in allWorkspaces[0].MappedPaths)
                {
                    sb.Append(map + ";");
                }

                this.MappedLocalFolder.Text = sb.ToString();
                this.GlobalPermissions.Text = string.Join(", ", globalperms);
                this.EffectivePermissions.Text = string.Join(", ", effectiveperms);

                ////WorkingFolder[] wf = TeamFoundationContext.Workspace.Folders;
            }));
        }

        #endregion
    }
}
